import React, { Component } from "react";
import { Tabs, Input, Button, Spin, Switch, InputNumber } from 'antd';
import { hospitalOrderInfoPage, hospitalOrderViewByQrCode } from '@/request/reservation';
import { exportSheetTable } from '@/utils/exportTable.js'
import TheTable from '@/components/TheTable';
import thirdParty from '@/assets/images/thirdParty.png';
import TheButton from "@/components/TheButton";
import ThePagination from '@/components/ThePagination';
import TheQueryForm from "@/components/TheQueryForm"
import './style/style.less';
import { getDateTime3 } from "@/utils/getDate"
import TheImage from '@/components/TheImage';
import CashierModal from './components/CashierModal';
import { scanEvent } from '@/utils/getCode'
import store from "@/store/store"
import moment from 'moment'
const dateFormat = 'YYYY/MM/DD';


const { TabPane } = Tabs
const { TextArea } = Input;
export default class AfterSales extends Component {
  constructor(props) {
    super();
    this.queryFormRef = React.createRef()
    this.state = {
      thirdLoading: false,
      defaultActiveKey: '',
      salesStatus: '',
      exportData: [],//打印的数据
      columns: [
        {
          title: "创建时间",
          dataIndex: "createTime",
          key: "createTime",
        },
        {
          title: "订单编号",
          dataIndex: "orderCode",
          key: "orderCode",
        },
        {
          title: "预约医生",
          dataIndex: "doctorName",
          key: "doctorName",
        },
        {
          title: "医生联系方式",
          dataIndex: "doctorMobile",
          key: "doctorMobile",
        },
        {
          title: "会员昵称",
          dataIndex: "nickName",
          key: "nickName",
        },
        {
          title: "会员手机号",
          dataIndex: "memberMobile",
          key: "memberMobile",
        },
        {
          title: "预约时间",
          dataIndex: "appointmentTime",
          key: "appointmentTime",
        },
        {
          title: "预约状态",
          dataIndex: "orderState",
          key: "orderState",
          render: (text, record) => {
            let label = ''
            switch (record.orderState) {
              case '1':
                label = "待支付"
                break
              case '2':
                label = "待使用"
                break
              case '9':
                label = "已完成"
                break
              case '0':
                label = "订单关闭"
                break
              default:
                label = "未知预约状态"
            }
            return label;
          }
        },
        {
          title: "预约门店",
          dataIndex: "storeDetail",
          key: "storeDetail",
        },
        {
          title: "订单金额（元）",
          dataIndex: "orderPrice",
          key: "orderPrice",
          render: (text, render) => {
            return <React.$Price price={render.orderPrice} />
          }
        },
        {
          title: "实付金额(元)",
          dataIndex: "payPrice",
          key: "payPrice",
          render: (text, render) => {
            return <React.$Price price={render.payPrice} />
          }
        },
        {
          title: "支付方式",
          dataIndex: "payWay",
          key: "payWay",
          render: (text, render) => {
            let payWay = ''
            switch (render.payWay) {
              case 'WeChat':
                payWay = '微信'
                break;
              case 'Alipay':
                payWay = '支付宝'
                break;
              case 'UnionPay':
                payWay = "银联"
                break;
              case 'YsPay':
                payWay = "银行卡支付"
                break;
                case 'RemoteAlipay':
                 payWay = "扫码支付（支付宝）"
                  break;
              case 'RemoteWeChat':
              payWay = "扫码支付（微信）"
                  break;
              default:
                payWay = "未知支付方式"
            }
            return payWay
          }
        },
        {
          title: "退款状态",
          dataIndex: "salesReturnStatus",
          key: "salesReturnStatus",
          render: (text, record) => {
            let label = ''
            switch (record.salesReturnStatus) {
              case '1':
                label = "有退款:退款中"
                break
              case '4':
                label = "有退款：退款失败"
                break
              case '9':
                label = "有退款:退款成功"
                break
              case '0':
                label = "有退款:退款关闭"
                break
              default:
                label = ""
            }
            return label;
          }
        },
        {
          title: "支付时间",
          dataIndex: "payTime",
          key: "payTime",
        },
        {
          title: "核销时间",
          dataIndex: "finishTime",
          key: "finishTime",
        },
        // {
        //   title: "备注",
        //   dataIndex: "remark",
        //   key: "remark",
        // },
        {
          title: "操作",
          fixed: "right",
          render: (text, render) => {
            return (
              <div>
                <TheButton hasPermi={['doctor:reservation:view']}
                  onClick={() => this.props.history.push(`/doctor/reservation/detials/${render.hospitalOrderId}`)}>
                  查看订单
                </TheButton>
              </div>
            );
          },
        },
      ],
      tabData: [
        {
          key: "",
          tab: '全部'
        },
        {
          key: '1',
          tab: '待支付'
        },
        {
          key: '2',
          tab: '待使用'
        },
        {
          key: '9',
          tab: '已完成'
        },
        {
          key: '0',
          tab: '订单关闭'
        },
      ],
      thirdPartyVisible: false,
      searchOption: [
        {
          field: 'search',
          label: '搜索',
          placeholder: '请输入搜索关键字',
          required: false,
          rules: [],
          type: 'InputGroupSSelect',
          options: [
            { value: "doctorMobile", label: '医生手机号' },
            { value: "doctorName", label: '医生姓名' },
            { value: "memberMobile", label: '会员手机号' },
            { value: "nickName", label: '会员昵称' },
          ],
        },
        { field: 'orderCode', label: '订单编号', placeholder: '请输入订单编号', required: false, rules: [], type: 'Input' },
        { field: 'time', label: '预约时间', placeholder: '请选择', required: false, rules: [], type: 'RangePicker' },
        {
          field: 'salesReturnStatus',
          label: '是否有退款',
          placeholder: '请选择',
          required: false,
          rules: [],
          type: 'Select',
          options: [
            { value: 1, label: '退款中' },
            { value: 4, label: '退款失败' },
            { value: 9, label: '退款成功' },
            { value: 0, label: '退款关闭' }
          ],
          // initialValues: 0
        },
      ],
      queryForm: {},
      dataSource: [],
      pageData: {
        pageNo: 1,
        pageSize: 10
      },
      exportPage: {
        pageNo: 1,
        pageSize: -1
      },
      salesReturnStatus: '',
      orderState: '',
      vtCode: '',
    }
  }

  //Initialization
  componentDidMount() {
    // this.queryFormRef.onSetDefault({
    //   time: [moment('2020-01-01'), moment('2020-01-02')]
    //   // time: [moment(startT).format(dateFormat), moment(endT).format(dateFormat)],
    //   // time: [moment(startT, dateFormat), moment(endT, dateFormat)],
    //   // startTime: startT,
    //   // endTime: endT
    // })
    let searchParams = store.getState().searchValue
    console.log(searchParams);
    if (!searchParams) {
      this.getData()
      return
    }
    let { pageNo, pageSize, queryForm, pathName, orderState } = searchParams
    if (searchParams && pageNo && pathName == 'doctor') {
      let startT = '', endT = '';
      if (queryForm && queryForm.time) {
        startT = getDateTime3(queryForm.time[0])
        endT = getDateTime3(queryForm.time[1])
        queryForm.time = [moment(startT, dateFormat), moment(endT, dateFormat)]
        // this.setState({
        //   time: [moment(startT, dateFormat), moment(endT, dateFormat)],
        //   startTime: moment(startT, dateFormat),
        //   endTime: moment(endT, dateFormat)
        // }, () => {
        // })
        this.queryFormRef.onSetDefault({
          time: [moment(startT, dateFormat), moment(endT, dateFormat)],
        })
      }
      this.setState({
        queryForm: {
          ...queryForm,
          // time: queryForm.time ? [moment(startT || '', dateFormat), moment(endT || '', dateFormat)] : [],
          // startTime: moment(startT || '', dateFormat),
          // endTime: moment(endT || '', dateFormat)
          // time: [moment(startT).format(dateFormat), moment(endT).format(dateFormat)],
        },
        pageData: {
          pageNo: pageNo,
          pageSize: pageSize
        }
      }, () => {
        // console.log([moment(startT).format(dateFormat), moment(endT).format(dateFormat)], 222222222222);
        this.queryFormRef.onSetDefault({
          ...queryForm,
          // time: queryForm.time ? [moment(startT || '', dateFormat), moment(endT || '', dateFormat)] : [],
        })

        this.setState({
          orderState,
          defaultActiveKey: orderState || '',
          salesStatus: orderState || '',
        }, (() => {
          console.log(this.state.queryForm);
          this.getData({
            ...this.state.queryForm,
            // endTime: this.state.queryForm.endTime != 'NaN-NaN-NaN' ? this.state.queryForm.endTime : '',
            // startTime: this.state.queryForm.startTime.toString() != 'NaN-NaN-NaN' ? this.state.queryForm.startTime : '',
            orderState
          })
        }
        ))

      })
    } else {
      this.getData()
    }
    if (!window.a) {
      window.addEventListener('keypress', this.scanWrapper, false);
      window.a = 1
    }
  }
  componentWillUnmount() {
    window.removeEventListener('keypress', this.scanWrapper, false);
    window.a = 0
  }
  scanWrapper = (e) => {
    scanEvent(e, async (code) => {
      // 监听了键盘输入或扫码枪
      let res = await hospitalOrderViewByQrCode({
        qrCode: code
      })
      if (res.code === 0) {
        this.props.history.push(`/doctor/reservation/detials/${res.data.hospitalOrderId}`)
      }
    });
  }
  //CTRL
  //data
  // getData = async () => {
  //   const { orderState, searchValue } = this.state
  //   let res = await hospitalOrderInfoPage({
  //     orderState: orderState,
  //     ...searchValue,
  //     ...this.state.pageData
  //   })
  //   if (res.data && res.code === 0) {
  //     this.setState({
  //       pageData: {
  //         pageNo: res.pageNo,
  //         pageSize: res.pageSize
  //       },
  //       dataSource: res.data,
  //       total: res.totalCount,
  //       loading: false
  //     })
  //   } else {
  //     this.setState({ loading: false })
  //   }
  // }
  // 输入框内容
  vtCodeValue = (v) => {
    this.setState({
      vtCode: v.target.value
    })
  }
  // 条形码数字
  vtCodeClick = async (e) => {
    this.setState({
      vtCode: e
    })
    let res = await hospitalOrderViewByQrCode({
      vtCode: this.state.vtCode
    })
    if (res.code === 0) {
      this.props.history.push(`/doctor/reservation/detials/${res.data.hospitalOrderId}`)
    }
  }
  getData = async (values, exportFlag = true) => {
    console.log(exportFlag, exportFlag);
    let pageNo;
    let pageSize;
    if (exportFlag) {
      pageSize = this.state.pageData.pageSize
      pageNo = this.state.pageData.pageNo
    } else {
      pageSize = -1;
      pageNo = 1;
    }
    if (values && values.orderState) {
      this.setState({
        orderState: values.orderState
      })
    }

    const { orderState } = this.state
    if (values && values.search) {
      values[values.search.Select] = values.search.Input || ''
      delete values.search;
    }
    console.log(values);
    if (values && values.time && values.time.length > 0) {
      values.startTime = getDateTime3(values.time[0])
      values.endTime = getDateTime3(values.time[1])
    }

    this.setState({
      queryForm: values === undefined ? this.state.queryForm : { ...values }
    }, async () => {
      const params = {
        pageNo,
        pageSize,
        ...this.state.queryForm,
        orderState,
        type: 'Y',
      }
      // store.dispatch({
      //   type: 'SaveSearchValues',
      //   data: {
      //     pathName: 'outPut',
      //     ...params
      //   }
      // })
      let res = await hospitalOrderInfoPage({
        ...params
      })
      if (exportFlag) {
        if (res.data && res.code === 0) {
          this.setState({
            pageData: {
              pageNo: res.pageNo,
              pageSize: res.pageSize
            },
            dataSource: res.data,
            total: res.totalCount,
            loading: false
          })
        } else {
          this.setState({ loading: false })
        }
      } else {
        this.setState({
          exportData: res.data,

        })
        this.exportGoodsDetail()
      }
    })
  }
  //搜索getValue
  getValue = (value) => {
    this.setState({
      pageData: {
        pageNo: 1,
        pageSize: 10
      },
      searchValue: value
    }, () => {
      this.getData()
    })
  }

  //tab切换
  changeKey = (orderState) => {
    store.dispatch({
      type: 'SaveSearchValues',
      data: {
        pathName: 'doctor',
        orderState,
        ...this.state.pageData,
        queryForm: this.state.queryForm,
      }
    })
    this.setState({
      orderState,
      salesStatus: orderState || '',
    }, () => {
      this.getData()
    })
  }

  //换页
  pageChange = (pageNo, pageSize) => {
    this.setState({
      pageData: {
        pageNo,
        pageSize
      }
    }, () => {
      store.dispatch({
        type: 'SaveSearchValues',
        data: {
          pathName: 'doctor',
          orderState: this.state.orderState,
          ...this.state.pageData,
          queryForm: this.state.queryForm,
        }
      })
      this.getData()
    })
  }


  chargebackRefused = (orderId) => {
    this.setState({ visible: true, orderId })
  };

  handleCancel = () => {
    this.setState({
      visible: false,
      orderId: ''
    })
  }
  onFormSearch(values) {
    console.log(values);
    this.setState({
      pageData: { pageNo: 1, pageSize: 10 }
    }, () => {
      store.dispatch({
        type: 'SaveSearchValues',
        data: {
          pathName: 'doctor',
          queryForm: {
            ...values
          },
          ...this.state.pageData,
          orderState: this.state.orderState
        }
      })

      this.getData(values)
    })
  }
  onReset() {
    this.setState({
      queryForm: {}
    }, () => {
      this.pageChange(1, 10)
    })
  }
  showCashierModal = (e) => {
    e.target.blur()
    // window.addEventListener('keypress', this.scanWrapper, false);
    this.setState({
      thirdPartyVisible: true,
    })
  }

  //三方支付dialog关闭
  thirdPartyDialogClose = () => {
    // window.removeEventListener('keypress', this.scanWrapper, false);
    this.setState({ thirdPartyVisible: false })
  }
  exportGoodsDetail() {

    const th_arr = [
      {
        title: "创建时间",
        prop: "createTime",
      },
      {
        title: "订单编号",
        prop: "orderCode",
      },
      {
        title: "预约医生",
        prop: "doctorName",
      },
      {
        title: "医生联系方式",
        prop: "doctorMobile",
      },
      {
        title: "会员昵称",
        prop: "nickName",
      },
      {
        title: "会员手机号",
        prop: "memberMobile",
      },
      {
        title: "预约时间",
        prop: "appointmentTime",
      },
      {
        title: "预约状态",
        prop: "orderState",

      },
      {
        title: "订单金额（元）",
        prop: "orderPrice",
      },
      {
        title: "预约门店",
        prop: "storeDetail",
      },
      {
        title: "实付金额(元)",
        prop: "payPrice",
      },
      {
        title: "支付方式",
        prop: "payWay",
      },
      {
        title: "退款状态",
        prop: "salesReturnStatus",
      },
      {
        title: "支付时间",
        prop: "payTime",
      },
      {
        title: "核销时间",
        prop: "finishTime",
      },
      // {
      //   title: "备注",
      //   prop: "remark",
      // },
    ]
    const tb_arr = this.state.exportData.map(item => {
      switch (item.orderState) {
        case '1':
          item.orderState = "待支付"
          break
        case '2':
          item.orderState = "待使用"
          break
        case '9':
          item.orderState = "已完成"
          break
        case '0':
          item.orderState = "订单关闭"
          break
        default:
          item.orderState = "未知预约状态"
      }
      switch (item.payWay) {
        case 'WeChat':
          item.payWay = '微信'
          break;
        case 'Alipay':
          item.payWay = '支付宝'
          break;
        case 'UnionPay':
          item.payWay = "银联"
          break;
        case 'YsPay':
          item.payWay = "银行卡支付"
          break;
          case 'RemoteAlipay':
            item.payWay = "扫码支付（支付宝）"
            break;
        case 'RemoteWeChat':
          item.payWay = "扫码支付（微信）"
            break;
        default:
          item.payWay = "未知支付方式"
      }

      switch (item.salesReturnStatus) {
        case '1':
          item.salesReturnStatus = "有退款:退款中"
          break
        case '4':
          item.salesReturnStatus = "有退款:退款失败"
          break
        case '9':
          item.salesReturnStatus = "有退款:退款成功"
          break
        case '0':
          item.salesReturnStatus = "有退款:退款关闭"
          break
        default:
          item.salesReturnStatus = ""
      }
      item.orderPrice = React.$transNum(item.orderPrice, 2, -2)
      item.payPrice = React.$transNum(item.payPrice, 2, -2)
      return item
    })

    exportSheetTable({ fileName: `医院预约列表`, tH_data: th_arr, tB_data: tb_arr, isSheet: true, merge: false, })
  }
  //VIEW
  render() {
    const { vtCode, tabData, thirdLoading, columns, dataSource, pageData, total, salesStatus, searchOption, thirdPartyVisible, defaultActiveKey } = this.state
    return (
      <div>
        <div className="p-layout-box pagebg">
          <TheButton type="primary" size='default' hasPermi={['doctor:reservation:reservation']} className="VerBtn" onClick={(e) => this.showCashierModal(e)} >核销</TheButton>
          <TheQueryForm ref={(ref) => this.queryFormRef = ref} show={true} option={searchOption}
            onGetValues={(values) => this.onFormSearch(values)}
            onReset={(values) => this.onReset(values)}
          >
            <TheButton type="default" size='default' hasPermi={['doctor:reservation:export']} onClick={() => this.getData(undefined, false)}>导出</TheButton>
          </TheQueryForm>

          <Tabs activeKey={salesStatus} defaultActiveKey={defaultActiveKey} onChange={(value) => this.changeKey(value)} >
            {/* tabBarExtraContent={<SearchHeader ref={this.SearchHeaderRef} getValue={this.getValue} />} */}
            {tabData.map(v => {
              return <TabPane key={v.key} tab={v.tab}>
                <div className="p-layout-content-pagination">
                  <TheTable scroll={{ x: 'max-content', y: "51vh" }} columns={columns} dataSource={dataSource} />
                  <ThePagination
                    pageNo={pageData.pageNo}
                    pageSize={pageData.pageSize}
                    total={total}
                    pageChange={this.pageChange}
                  />
                </div>
              </TabPane>
            })}
          </Tabs>
          <CashierModal
            title="扫码核销"
            width={600}
            visible={thirdPartyVisible}
            onCancel={this.thirdPartyDialogClose}
            footer={
              <div className='completion-button-group'>
                <div onClick={this.thirdPartyDialogClose} className='dialog-footer-button'>
                  <div>取消核销</div>
                </div>
              </div>
            }
          >
            <Spin spinning={thirdLoading}>
              <div className='third-party-box'>
                <TheImage src={thirdParty} width={306} height={188} preview={false} />
                <div>请使用扫码枪，扫码客户的宠物医院预约的医生咨询订单二维码</div>
                <div className="third-party-input">
                  <Input type="number" size='middle' style={{ width: 200 }} placeholder='输入条形码数字' onChange={(e) => { this.vtCodeValue(e) }} />
                  <Button className="third-party-btn" type="large" onClick={() => { this.vtCodeClick(vtCode) }}>查询</Button>
                </div>

              </div>
            </Spin>
          </CashierModal>
        </div >
      </div>
    )
  }
}
